/**
   CheckCode
 * Time:2018年6月29日
 */
package com.ssm.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 15199
 *
 */
/*产生验证码*/
public class CheckCode {
	
	public void CreateCheckCode(HttpServletRequest request,HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		response.setContentType("image/jpeg");
		StringBuilder builderCode = new StringBuilder();
		//定义画布的宽高
		int width = 100;
		int height = 32;

		//创建画板
		BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);

		//获取画布
		Graphics g = image.getGraphics();

		//设置画笔的颜色
		g.setColor(Color.white);

		//填充画布
		g.fillRect(0, 0, width, height);


		//定义验证码的范围
		char words [] = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
		//012345
		//随机选取  创建随机对象
		Random rnd = new Random();

		//画4次
		for (int i = 0; i < 4; i++) {

			//设置画笔的颜色  随机一个颜色 rnd.nextInt(256) 随机一个0-255的int   
			g.setColor(new Color(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
			//设置字体
			g.setFont(new Font("宋体", Font.BOLD, 20));
			char c =words [rnd .nextInt(words .length)];
			builderCode.append(c);

			//画验证码
			g.drawString(c+"", i*15+20,20 );
		}

		// 画干扰点
		for (int i = 0; i < 50; i++) {
			g.setColor(new Color(rnd.nextInt(255), rnd.nextInt(255), rnd
					.nextInt(255)));
			g.drawOval(rnd.nextInt(width), rnd.nextInt(height), 1, 2);
		}

		for (int i = 0; i < 5; i++) {
			g.setColor(new Color(rnd.nextInt(255), rnd.nextInt(255), rnd.nextInt(255)));
			g.drawLine(rnd.nextInt(width), rnd.nextInt(height),
					rnd.nextInt(width), rnd.nextInt(height));
		}


		//将画布图片响应给页面  通过流
		OutputStream outputStream = response.getOutputStream();



		ImageIO.write(image, "jpeg", outputStream);
		outputStream.flush();
		//6.保存到session中

		request.getSession().setAttribute("CheckCode", builderCode.toString());



	}
}
